import turtle

# 创建一个窗口和画笔
screen = turtle.Screen()
screen.bgcolor("white")

pen = turtle.Turtle()
pen.speed(0)

# 谢尔宾斯基三角形递归函数
def sierpinski(points, depth):
    # 定义三种颜色
    colors = ['blue', 'red', 'green']
    
    # 绘制填充三角形
    pen.fillcolor(colors[depth % 3])
    pen.up()
    pen.goto(points[0][0], points[0][1])
    pen.down()
    pen.begin_fill()
    pen.goto(points[1][0], points[1][1])
    pen.goto(points[2][0], points[2][1])
    pen.goto(points[0][0], points[0][1])
    pen.end_fill()
    
    # 如果深度大于0，则继续细分
    if depth > 0:
        # 计算三边中点
        mid1 = [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2]
        mid2 = [(points[1][0] + points[2][0]) / 2, (points[1][1] + points[2][1]) / 2]
        mid3 = [(points[2][0] + points[0][0]) / 2, (points[2][1] + points[0][1]) / 2]
        
        # 递归绘制三个子三角形
        sierpinski([points[0], mid1, mid3], depth-1)
        sierpinski([points[1], mid1, mid2], depth-1)
        sierpinski([points[2], mid2, mid3], depth-1)

# 设置初始三角形顶点
points = [[0, 200], [-173, -100], [173, -100]]

# 绘制谢尔宾斯基三角形
sierpinski(points, 5)

# 点击关闭窗口
screen.exitonclick()